package com.bang.springcloud.report.task;

import com.alibaba.fastjson.JSONObject;
import com.bang.framework.mq.constants.QueueConstants;
import com.bang.springcloud.report.entity.BrokerMessageLog;
import com.bang.springcloud.report.entity.Order;
import com.bang.springcloud.report.entity.constants.Constants;
import com.bang.springcloud.report.mapper.BrokerMessageLogMapper;
import com.bang.springcloud.report.util.OrderSendUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class RetryMessageTasker {


    @Autowired
    private OrderSendUtils rabbitOrderSender;

    @Autowired
    private BrokerMessageLogMapper brokerMessageLogMapper;

    @Scheduled(initialDelay = 3000, fixedDelay = 10000)
    public void reSend() {
        log.info("---------------定时任务开始---------------");
        //pull status = 0 and timeout message
        List<BrokerMessageLog> list = brokerMessageLogMapper.query4StatusAndTimeoutMessage();
        list.forEach(messageLog -> {
            String messageId = messageLog.getMessageId();
            if (messageLog.getTryCount() >= 3) {
                //update fail message
                brokerMessageLogMapper.changeBrokerMessageLogStatus(messageId, Constants.ORDER_SEND_FAILURE, LocalDateTime.now());
            } else {
                // resend
                brokerMessageLogMapper.update4ReSend(messageId, LocalDateTime.now());
                Order reSendOrder = JSONObject.parseObject(messageLog.getMessage(), Order.class);
                try {
                    CorrelationData correlationData = new CorrelationData(messageId);
                    rabbitOrderSender.send(reSendOrder, correlationData, QueueConstants.Queue.BANG_TEST_DEFAULT_QUEUE);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("-----------异常处理-----------");
                }
            }
        });

    }


}
